<?php
/**
 * @project kkzc
 * @date 2015-7-25
 * @author xialei <xialeistudio@gmail.com>
 */

namespace app\module\api\controllers;


use app\models\Order;
use app\models\User;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;

class OrderController extends BaseController
{
    public $modelClass = 'app\models\Order';

    /**
     * @author xialei <xialeistudio@gmail.com>
     * @param string $action
     * @param Order $model
     * @param array $params
     * @throws ForbiddenHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        if (\Yii::$app->admin->isGuest && $model != null && $model->user_id != \Yii::$app->user->id && !\Yii::$app->request->isOptions) {
            throw new ForbiddenHttpException();
        }
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['delete']);
        $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
        return $actions;
    }

    public function prepareDataProvider()
    {
        $userIds = [\Yii::$app->user->id];
        //一级
        $primary = User::find()->where(['parent_id' => \Yii::$app->user->id, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //二级
        $secondary = User::find()->where(['parent_id' => $primary, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //三级
        $third = User::find()->where(['parent_id' => $secondary, 'role' => User::ROLE_TENANTS])->select(['user_id'])->column();
        //合并用户ID
        $userIds = ArrayHelper::merge($userIds, $primary, $secondary, $third);
        return new ActiveDataProvider([
            'query' => Order::find()->where(['{{%order}}.user_id' => $userIds, 'state' => Order::STATE_SETTLEMENT])->orderBy(['repay_at' => SORT_DESC])
        ]);
    }
}